<div class="layui-card">
    <div class="layui-card-header">
        <h2 class="header-title">应用管理</h2>
        <span class="layui-breadcrumb pull-right">
          <a href="#!console">首页</a>
          <a><cite>应用管理</cite></a>
        </span>
    </div>
    <div class="layui-card-body">
        <div class="layui-form toolbar">
            搜索：
            <select id="app-search-key">
                <!--                <option value="">-请选择-</option>-->
                <option value="name">名称</option>
            </select>&emsp;
            <input id="app-edit-value" class="layui-input search-input" type="text" placeholder="输入关键字"/>&emsp;
            <button id="app-btn-search" class="layui-btn icon-btn"><i class="layui-icon">&#xe615;</i>搜索</button>
            <button id="app-btn-add" class="layui-btn icon-btn"><i class="layui-icon">&#xe654;</i>添加</button>
        </div>

        <!-- 数据表格 -->
        <table class="layui-table" id="app-table" lay-filter="app-table"></table>
    </div>
</div>
<!--添加应用表格-->
<script type="text/html" id="appAndEntmodel">
    <table class="layui-table" id="AppAddEntTable" lay-filter="AppAddEntTable"></table>
</script>
<!--删除企业应用表格-->
<script type="text/html" id="appDelEntAppmodel">
    <table class="layui-table" id="AppDelEntTable" lay-filter="AppDelEntTable"></table>
</script>

<!-- 表单弹窗 -->
<script type="text/html" id="app-model">
    <form id="app-form" lay-filter="app-form" class="layui-form model-form">
        <input name="app_id" type="hidden"/>
        <input name="ea_id" type="hidden"/>
        <div class="layui-form-item">
            <label class="layui-form-label">应用名称</label>
            <div class="layui-input-block">
                <input name="name" placeholder="请输入应用名称" type="text" class="layui-input" maxlength="20"
                       lay-verify="required" required/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">描述</label>
            <div class="layui-input-block">
                <input name="des" placeholder="请输入描述" type="text" class="layui-input"/>
            </div>
        </div>
        <div class="layui-form-item">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                <input name="remark" placeholder="请输入备注" type="text" class="layui-input"/>
            </div>
        </div>
        <div class="layui-form-item model-form-footer">
            <button class="layui-btn layui-btn-primary" ew-event="closeDialog" type="button">取消</button>
            <button class="layui-btn" lay-filter="app-form-submit" lay-submit>保存</button>
        </div>
    </form>
</script>

<!-- 表格操作列 -->
<script type="text/html" id="app-table-bar">
    <a class="layui-btn layui-btn-primary layui-btn-xs" lay-event="edit">修改</a>
    <a class="layui-btn layui-btn-danger layui-btn-xs" lay-event="del">删除</a>
    <a class="layui-btn layui-btn-xs" lay-event="auth">授权管理</a>
    <a class="layui-btn layui-btn-xs" lay-event="delEntInApp">开通管理</a>
</script>

<script>
    layui.use(['form', 'table', 'util', 'config', 'admin', 'formSelects', 'layer'], function () {
        var form = layui.form;
        var table = layui.table;
        var config = layui.config;
        var layer = layui.layer;
        var util = layui.util;
        var admin = layui.admin;
        var formSelects = layui.formSelects;
        var apiEnt = "api-sys/api/sysApp/";
        //渲染表格
        let myTable = table.render({
            elem: '#app-table',
            url: config.base_server + 'api-sys/api/sysApp/list',
            where: {
                access_token: config.getToken().access_token
            },
            page: true,
            cols: [[
                {type: 'numbers'},
                {field: 'app_id', sort: true, title: 'ID', width: 80},
                {field: 'name', sort: true, title: '应用名称'},
                {field: 'des', sort: true, title: '描述', width: 100},
                {field: 'remark', sort: true, title: '备注', width: 100},
                {field: 'createDate', sort: true, title: '创建时间'},
                {align: 'center', toolbar: '#app-table-bar', title: '操作', width: 400}
            ]]
        });

        // 添加按钮点击事件
        $('#app-btn-add').click(function () {
            showEditModel();
        });

        // 表单提交事件
        form.on('submit(app-form-submit)', function (data) {
            layer.load(2);
            if (data.field.app_id) {
                admin.req('api-sys/api/sysApp/update', JSON.stringify(data.field), function (data) {
                    layer.closeAll('loading');
                    console.log(data);
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        table.reload('app-table');
                        layer.closeAll('page');
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'PATCH');
            } else {
                admin.req('api-sys/api/sysApp/add', JSON.stringify(data.field), function (data) {
                    layer.closeAll('loading');
                    console.log(data);
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        table.reload('app-table');
                        layer.closeAll('page');
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'POST');
            }

            return false;
        });

        // 工具条点击事件
        table.on('tool(app-table)', function (obj) {
            var data = obj.data;
            if (obj.event === 'edit') { //修改
                showEditModel(data);
            } else if (obj.event === 'del') { //删除
                doDelete(obj);
            } else if (obj.event === 'auth') {  // 权限管理
                showAuthModel(data);
            }else if (obj.event==='delEntInApp'){//开通管理
                showDelEntAppModel(data);
            }
        });
        // todo 搜索按钮点击事件（添加token）
        $('#app-btn-search').click(function () {
            var key = $('#app-search-key').val();
            var value = $('#app-edit-value').val();
            var data = {};
            data[key] = value;
            console.log(data)
            // table.reload('app-table', {where: data});
            myTable.reload({where: data});
        });

        // 显示编辑弹窗
        var showEditModel = function (data) {
            layer.open({
                type: 1,
                title: data ? '修改应用' : '添加应用',
                area: '450px',
                offset: '120px',
                content: $('#app-model').html(),
                success: function () {
                    $('#app-form')[0].reset();
                    $('#app-form').attr('method', 'POST');
                    if (data) {
                        // $("input[name='appKey']").attr('disabled',true);
                        // $("input[name='appKey']").attr('class',"layui-input layui-disabled");
                        form.val('app-form', data);
                        $('#app-form').attr('method', 'POST');
                    }
                }
            });
        };

        // 删除
        var doDelete = function (obj) {
            layer.confirm('确定要删除吗？', function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('api-sys/api/sysApp/del/' + obj.data.app_id, {}, function (data) {
                    layer.closeAll('loading');
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        obj.del();
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'DELETE');
            });
        };
        // 删除企业应用
        var delapp = function (obj) {
            layer.confirm('确定要删除吗？', function (i) {
                layer.close(i);
                layer.load(2);
                admin.req('api-sys/api/entApp/del?ent_id=' + obj.data.ent_id+'&app_id='+obj.data.app_id, {}, function (data) {
                    layer.closeAll('loading');
                    if (data.code == 0) {
                        layer.msg(data.msg, {icon: 1, time: 500});
                        obj.del();
                    } else {
                        layer.msg(data.msg, {icon: 2, time: 500});
                    }
                }, 'DELETE');
            });
        };
        // 显示添加应用弹窗
        var showAuthModel = function (data) {
            var open = layer.open({
                id: 'entAddAppList',
                type: 1,
                title: '授权应用',
                area: '600px',
                offset: '120px',
                content: $('#appAndEntmodel').html(),
                success: function () {
                    table.render({
                        elem: '#AppAddEntTable',
                        where: {access_token: config.getToken().access_token},
                        url: config.base_server + apiEnt + 'listEntNotInApp?app_id=' + data.app_id,
                        cols: [[
                            {type: 'checkbox', fixed: 'left'},
                            {field: 'ent_id', sort: true, title: '企业ID'},
                            {field: 'name', sort: true, title: '企业名称'},
                        ]]
                    });
                }, btn: ['添加', '关闭'],
                yes: function (index, layero) {
                    var checkData = table.checkStatus("AppAddEntTable");
                    var checkUsers = checkData.data;
                    console.log(checkUsers);
                    if (!checkUsers || checkUsers.length == 0) {
                        layer.msg("至少选一个", {icon: 2, time: 1500});
                        return;
                    }
                    var reqData = [];
                    checkUsers.forEach(function (item, index) {
                        reqData[index] = {ent_id: item.ent_id, app_id: data.app_id};
                    });
                    layer.load(2);
                    admin.req('api-sys/api/entApp/addBatch/', JSON.stringify(reqData), function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 1000});
                            table.reload('app-table');
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 3000});
                        }
                        layer.close(open);
                    }, 'POST');
                }, btn2: function (index, layero) {
                    layer.close(open);
                }
            });
        };
        // 显示开通管理应用弹窗
        var showDelEntAppModel = function (data) {
            var open = layer.open({
                id: 'entDelEntAppList',
                type: 1,
                title: '开通管理',
                area: '600px',
                offset: '120px',
                content: $('#appDelEntAppmodel').html(),
                success: function () {
                    table.render({
                        elem: '#AppDelEntTable',
                        where: {access_token: config.getToken().access_token},
                        url: config.base_server  + 'api-sys/api/entApp/list?app_id=' + data.app_id,
                        cols: [[
                            {type: 'checkbox', fixed: 'left'},
                            {field: 'ent_id', sort: true, title: '企业ID'},
                            {field: 'entname', sort: true, title: '企业名称'},
                        ]]
                    });
                },btn: ['删除', '关闭'],
                yes: function (index, layero) {
                    var checkData = table.checkStatus("AppDelEntTable");
                    var checkUsers = checkData.data;
                    console.log(checkUsers);
                    if (!checkUsers || checkUsers.length == 0) {
                        layer.msg("至少选一个", {icon: 2, time: 1500});
                        return;
                    }
                    var reqData = [];
                    checkUsers.forEach(function (item, index) {
                        // reqData[index] = {ent_id: item.ent_id, app_id: data.app_id};
                        reqData[index] =  item.ea_id;
                    });
                    layer.load(2);
                    admin.req('api-sys/api/entApp/delBatch/', JSON.stringify(reqData), function (data) {
                        layer.closeAll('loading');
                        if (data.code == 0) {
                            layer.msg(data.msg, {icon: 1, time: 1000});
                            table.reload('app-table');
                        } else {
                            layer.msg(data.msg, {icon: 2, time: 3000});
                        }
                        layer.close(open);
                    }, 'DELETE');
                }, btn2: function (index, layero) {
                    layer.close(open);
                }
            });
        };

    });

</script>